Security News
The Unpaid Backbone of Open Source: Solo Maintainers Face Increasing Security Demands
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
connect-redis
Advanced tools
The connect-redis npm package is a Redis session store for Express and Connect. It allows you to store session data in a Redis database, which can help with scaling applications by providing a centralized session store.
Basic Setup
This code demonstrates how to set up a basic Express application with connect-redis as the session store. It configures the session middleware to use Redis for storing session data.
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const express = require('express');
const app = express();
app.use(session({
store: new RedisStore({
host: 'localhost',
port: 6379
}),
secret: 'your secret',
resave: false,
saveUninitialized: false
}));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Custom Redis Client
This code demonstrates how to use a custom Redis client with connect-redis. This can be useful if you need to configure the Redis client with specific options or use an existing Redis client instance.
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const express = require('express');
const redis = require('redis');
const app = express();
const redisClient = redis.createClient({
host: 'localhost',
port: 6379
});
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'your secret',
resave: false,
saveUninitialized: false
}));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Advanced Configuration
This code demonstrates advanced configuration options for connect-redis, such as setting the time-to-live (ttl) for sessions and enabling error logging.
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const express = require('express');
const app = express();
app.use(session({
store: new RedisStore({
host: 'localhost',
port: 6379,
ttl: 260,
logErrors: true
}),
secret: 'your secret',
resave: false,
saveUninitialized: false
}));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
express-session is a general-purpose session middleware for Express. It supports various session stores, including in-memory, file-based, and database-backed stores. Unlike connect-redis, it does not provide a Redis-specific store out of the box but can be extended with other packages.
connect-mongo is a MongoDB session store for Express and Connect. It provides similar functionality to connect-redis but uses MongoDB as the backend store instead of Redis. It is useful for applications that already use MongoDB and want to keep session data in the same database.
express-mysql-session is a MySQL session store for Express. It provides similar functionality to connect-redis but uses MySQL as the backend store. It is useful for applications that use MySQL and want to store session data in a relational database.
connect-redis provides Redis session storage for Express. Requires Redis >= 2.0.0
.
npm:
npm install redis connect-redis express-session
Yarn:
yarn add redis connect-redis express-session
const session = require("express-session")
let RedisStore = require("connect-redis")(session)
// redis@v4
const { createClient } = require("redis")
let redisClient = createClient({ legacyMode: true })
redisClient.connect().catch(console.error)
// redis@v3
const { createClient } = require("redis")
let redisClient = createClient()
// ioredis
const Redis = require("ioredis")
let redisClient = new Redis()
app.use(
session({
store: new RedisStore({ client: redisClient }),
saveUninitialized: false,
secret: "keyboard cat",
resave: false,
})
)
The RedisStore
requires an existing Redis client. Any clients compatible with the redis
API will work. See client
option for more details.
An instance of redis
or a redis
compatible client.
Known compatible and tested clients:
legacyMode: true
)Key prefix in Redis (default: sess:
).
This prefix appends to whatever prefix you may have set on the client
itself.
Note: You may need unique prefixes for different applications sharing the same Redis instance. This limits bulk commands exposed in express-session
(like length
, all
, keys
, and clear
) to a single application's data.
If the session cookie has a expires
date, connect-redis
will use it as the TTL.
Otherwise, it will expire the session using the ttl
option (default: 86400
seconds or one day).
Note: The TTL is reset every time a user interacts with the server. You can disable this behavior in some instances by using disableTouch
.
Note: express-session
does not update expires
until the end of the request life cycle. Calling session.save()
manually beforehand will have the previous value.
Disables re-saving and resetting the TTL when using touch
(default: false
)
The express-session
package uses touch
to signal to the store that the user has interacted with the session but hasn't changed anything in its data. Typically, this helps keep the users session alive if session changes are infrequent but you may want to disable it to cut down the extra calls or to prevent users from keeping sessions open too long. Also consider enabling if you store a lot of data on the session.
Ref: https://github.com/expressjs/session#storetouchsid-session-callback
Disables key expiration completely (default: false
)
This option disables key expiration requiring the user to manually manage key cleanup outside of connect-redis
. Only use if you know what you are doing and have an exceptional case where you need to manage your own expiration in Redis. Note this has no effect on express-session
setting cookie expiration.
The encoder/decoder to use when storing and retrieving session data from Redis (default: JSON
).
interface Serializer {
parse(string): object
stringify(object): string
}
Value used for count parameter in Redis SCAN
command. Used for ids()
and all()
methods (default: 100
).
client.on("error", console.error)
By default, the redis
client will auto-reconnect on lost connections. But requests may come in during that time. In Express, one way you can handle this scenario is including a "session check":
app.use(session(/* setup session here */))
app.use(function (req, res, next) {
if (!req.session) {
return next(new Error("oh no")) // handle error
}
next() // otherwise continue
})
If you want to retry, here is another option.
FAQs
Redis session store for Connect
The npm package connect-redis receives a total of 444,627 weekly downloads. As such, connect-redis popularity was classified as popular.
We found that connect-redis demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
Security News
License exceptions modify the terms of open source licenses, impacting how software can be used, modified, and distributed. Developers should be aware of the legal implications of these exceptions.
Security News
A developer is accusing Tencent of violating the GPL by modifying a Python utility and changing its license to BSD, highlighting the importance of copyleft compliance.